package second.string;

public class Solution04 {
    public String reverseWords(String s) {
        StringBuffer sb = removeSpace(s);
        char[] chars = sb.toString().toCharArray();
        reverse(chars, 0, chars.length - 1);
        reverseEachWords(chars);
        return new String(chars);
    }

    public void reverse(char[] chars, int i, int j) {
        while (i < j) {
            char tmp = chars[i];
            chars[i] = chars[j];
            chars[j] = tmp;
            i++;
            j--;
        }
    }

    public StringBuffer removeSpace(String s) {
        int i = 0;
        int j = s.length() - 1;
        while (i < s.length() && s.charAt(i) == ' ') i++;
        while (j >= 0 && s.charAt(j) == ' ') j--;
        StringBuffer sb = new StringBuffer();
        while (i <= j) {
            char c = s.charAt(i);
            if (c != ' ' || sb.charAt(sb.length() - 1) != ' ') {
                sb.append(c);
            }
            i++;
        }
        return sb;
    }

    public void reverseEachWords(char[] chars) {
        int i = 0;
        int j = 1;
        while (i < chars.length) {
            while (j < chars.length && chars[j] != ' ') {
                j++;
            }
            reverse(chars, i, j - 1);
            i = j + 1;
            j = i + 1;
        }
    }
}
